#include "header.h"

int sock_mtu_eth, sock_mtu_can;

/***************创建socket***************/

//创建以太网socket端口
static void eth_socket_create(void)
{
	struct ifreq ifr;
	struct sockaddr_in addr;
	struct timeval timeout;

	sock_mtu_eth = socket(AF_INET, SOCK_DGRAM, 0);//IPv4,UDP类型
	/*
	//addr.sin_family = AF_INET;//IPv4
	//addr.sin_port = htons(3270);//本机端口号
	//addr.sin_addr.s_addr = inet_addr("192.168.1.251");//指定本机IP
	//bind(sock_mtu_eth, (struct sockaddr *)&addr, sizeof(addr));
	
	//struct ifreq ifr;
	//memset(&ifr, 0, sizeof(ifr));
	//strncpy(ifr.ifr_name, "enp2s0f1", IFNAMSIZ);//指定设备
	//setsockopt(sock_mtu_eth, SOL_SOCKET, SO_BINDTODEVICE, (char *)&ifr, sizeof(ifr));
    */
	timeout.tv_sec = 2;//超时时间2s
	timeout.tv_usec = 0;
	setsockopt(sock_mtu_eth, SOL_SOCKET, SO_RCVTIMEO, (char *)&timeout, sizeof(timeout));
}

//创建CAN的socket端口
static void can_socket_create(void)
{
	int loopback = 0;
	struct sockaddr_can addr;
	struct ifreq ifr;

	sock_mtu_can = socket(PF_CAN, SOCK_RAW, CAN_RAW);//原始套接字,原始CAN协议
	strcpy(ifr.ifr_name, "can0");//指定设备can0
	ioctl(sock_mtu_can, SIOCGIFINDEX, &ifr);

	addr.can_family = AF_CAN; 
	addr.can_ifindex = ifr.ifr_ifindex; 
	bind(sock_mtu_can, (struct sockaddr *)&addr, sizeof(addr));//绑定套接字
	setsockopt(sock_mtu_can, SOL_CAN_RAW, CAN_RAW_LOOPBACK, &loopback, sizeof(loopback));//关闭回环功能
}

static void socket_create(void)
{
	eth_socket_create();
	can_socket_create();
}

void write_file(char *connect)
{
	char line[30] = {0};
	FILE *fd = fopen("/home/wingo/loco_server/code/mccu/powerONOFF.txt", "a+");
	if (!fd)
		return;
	time_t ct = time(NULL);
	struct tm *bktime = localtime(&ct);
	strftime(line, sizeof(line), "%y-%m-%d %H:%M:%S ", bktime);
	strncat(line, connect, sizeof(line));
	fwrite(line, 1, strlen(line), fd);
	fflush(fd);
	fclose(fd);
}

/******************************/

int main(void)
{
    write_file("power-on\n");
	pthread_t tid_mtu_ccu, tid_ccu_mtu, tid_data_up;

	socket_create();

	pthread_create(&tid_mtu_ccu, NULL, mtu_ask_ccu, NULL);
	pthread_create(&tid_ccu_mtu, NULL, ccu_res_mtu, NULL);
	pthread_create(&tid_data_up, NULL, mtu_data_up, NULL);

	while (1);
	return 0;
}
